#!coding: utf-8
# Create your views here.
import math
import time
import os
import logging
import sys
import json
import uuid
import base64
import hashlib 
import random

from exceptions import Exception

from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django.template.loader import get_template
from django.template import Context
from django.shortcuts import render_to_response

from topapi import *

from settings import mdb, rdb, recrdb, statdb
import datamining

dlog = logging.getLogger('django')

def get_days(n=1):
    r = []
    for i in range(n):
        x = time.time() - (i+1) * 86400 
        x = time.strftime('%Y-%m-%d', time.localtime(x))
        r.append(x)
    return r

def session_redirect():
    return HttpResponseRedirect(TConfig.sessionUrl + TConfig.appkey)


def check_session_and_get_nick(request):
    s = request.COOKIES 
    g = request.GET 
    set_session_to_cookie = True
    top_session = g.get('top_session', '').strip()
    if not top_session:
        top_session = s.get('top_session', '').strip()
        set_session_to_cookie = False
    if not top_session: 
        dlog.warning('get top_session fail, need redirect to taobao to login')
        raise Exception('get top_session fail, need redirect to taobao to login')
    if set_session_to_cookie:
        top_parameters = g.get('top_parameters', '').strip()
        top_sign = g.get('top_sign', '').strip()
    else:
        top_parameters = s.get('top_parameters', '').strip()
        top_sign = s.get('top_sign', '').strip()
    param = check_session(TConfig.appkey, TConfig.appsecret, top_parameters, top_session, top_sign)
    param['set_session_to_cookie'] = set_session_to_cookie 
    datamining.check_new_user(mdb, param['nick'], param['top_session'])
    return param


def index(request):
    try:
        top_param = check_session_and_get_nick(request)
    except Exception as e:
        dlog.warning('check_session_and_get_nick fail: %s' %(repr(e)))
        return session_redirect()
    d = {
        'nick':top_param['nick'],
        'pagename':'index',
    }
    r = render_to_response('index.html', d)
    if top_param['set_session_to_cookie']:
        g = request.GET
        r.set_cookie('top_session', g.get('top_session', '')) 
        r.set_cookie('top_parameters', g.get('top_parameters', '')) 
        r.set_cookie('top_sign', g.get('top_sign', '')) 
        r.set_cookie('top_appkey', g.get('top_appkey', ''))
    return r

def help(request):
    try:
        top_param = check_session_and_get_nick(request)
    except Exception as e:
        dlog.warning('check_session_and_get_nick fail: %s' %(repr(e)))
        return session_redirect()
    d = {
        'nick':top_param['nick'],
        'pagename':'index',
    }
    r = render_to_response('help.html', d)
    if top_param['set_session_to_cookie']:
        g = request.GET
        r.set_cookie('top_session', g.get('top_session', '')) 
        r.set_cookie('top_parameters', g.get('top_parameters', '')) 
        r.set_cookie('top_sign', g.get('top_sign', '')) 
        r.set_cookie('top_appkey', g.get('top_appkey', ''))
    return r


#20111111->2011-11-11
def daychange(input):
    if len(input) != 8:
        return input
    return '-'.join([input[:4], input[4:6], input[6:]])


def report(request):
    try:
        top_param = check_session_and_get_nick(request)
    except Exception as e:
        dlog.warning('check_session_and_get_nick fail: %s' %(repr(e)))
        return session_redirect()
    nick = top_param['nick']
                
    pv30 = []
    click30 = []
    stat_days = []
  
    tmp_time = int (time.time() - 14*86400)
    for i in range(14):
        tmp_day = time.strftime('%Y%m%d', time.localtime(tmp_time+86400*i))
        stat_days.append(time.strftime('%m-%d', time.localtime(tmp_time+86400*i)))
        tmp_key = 'nick'+':'+tmp_day
        try:
            pv_tmp = statdb.dailyview.find_one({'_id':tmp_key}, fields=['view'])
            pv_tmp = pv_tmp['view']
        except:
            pv_tmp = 0
        pv30.append(pv_tmp)
        try:
            pv_tmp = statdb.dailyclick.find_one({'_id':tmp_key}, fields=['click'])
            pv_tmp = pv_tmp['click']
        except:
            pv_tmp = 0
        click30.append(pv_tmp)

    pv_tmp = statdb.totalstat.find_one({'_id':nick})

    pv_history = {
        'avg': sum(pv30)/14,
        'sum': pv_tmp['totalview'],
        'max': pv_tmp['maxview'],
        'day_max' : daychange(pv_tmp['maxviewday']),
    }
        
    click_history = {
        'avg': sum(click30)/14,
        'sum': pv_tmp['totalclick'],
        'max': pv_tmp['maxclick'],
        'day_max' : daychange(pv_tmp['maxclickday']),
    }

    d = {
        'nick':nick,
        'pv30':pv30,
        'click30':click30,
        'stat_days': stat_days,
        'pv_history':pv_history,
        'click_history':click_history,
        'pagename':'report',
    }

    r = render_to_response('report.html', d)
    if top_param['set_session_to_cookie']:
        g = request.GET
        r.set_cookie('top_session', g.get('top_session', '')) 
        r.set_cookie('top_parameters', g.get('top_parameters', '')) 
        r.set_cookie('top_sign', g.get('top_sign', '')) 
        r.set_cookie('top_appkey', g.get('top_appkey', ''))
    return r


def show(request):
    g = request.GET 
    nick = g.get('seller_nick', '').strip()
    try:
        width = int(g.get('module_width', '750'))
    except:
        width = 750
    rec_num =  (width == 950) and 9 or 7
    if not nick:
        return HttpResponse('no seller_nick')
    user = mdb.user.find_one({'_id':nick})
    if not user or 'type' not in user:
        user_type = 'C'
    else:
        user_type = user['type']
    shop_rec_list = mdb.shop_rec.find_one({'_id':nick})
    if not shop_rec_list:
        return HttpResponse('no recommender items')
    shop_rec_list = shop_rec_list['recs']
    items = []
    for rec in shop_rec_list:
        num_iid = rec['num_iid']
        item = mdb.items.find_one({'_id':num_iid}, fields=['num_iid', 'title', 'list_time', 'pic_url', 'has_discount', 'price', 'approve_status', 'nick'])
        if not item:
            continue
        if item['approve_status'] != 'onsale':
            continue
        item['price'] = float(item['price'])
        item['price_a'] = int(item['price'])
        item['price_b'] = '%02d' %(int( 100* (item['price'] - item['price_a'])))
        tmp_time = item['list_time'].split(' ')[0]
        item['time_distance'] = time.mktime(time.strptime(tmp_time, '%Y-%m-%d'))
        item['time_distance'] = int((time.time() - item['time_distance'] )/86400 )
        item['volumn'] = rec['trade_num']
        item['rates'] = rec['rate_num']
        item['rate_ct'] = []
        for oid in rec['rates']:
            traderate = mdb.traderate.find_one({'_id':oid}, fields = ['content', 'nick'])
            if not traderate:
                continue
            item['rate_ct'].append(traderate['content'])
        item['rec_score'] = rec['score']
        items.append(item)
        rec_num -= 1
        if rec_num <= 0:
            break
    d = {
        'type': user_type,
        'pagename':'iframe',
        'itemlist':items,
        'module_width':width,
    }

    url = request.get_full_path()
    meta = request.META 
    ip = meta['REMOTE_ADDR']
    iid_list = ','.join(str(i['_id']) for i in items)
    #return HttpResponse(json.dumps(items), mimetype='application/json')
    r = render_to_response('iframe.html', d)
    dlog.info("%s %s %s" %(ip, iid_list, url))
    return r



